package svgundoredo;

/**
 * This is the moving command
 */
import svgedit.svg.SVGCircleElement;
import svgedit.svg.SVGElement;
import svgedit.svg.SVGGroup;
import svgedit.svg.SVGLineElement;
import svgedit.svg.SVGRectElement;
import svgedit.svg.SVGVisitor;

public class MoveElementCommand extends AbstractCommand
{
    private SVGElement[] elements;
    
    private float x, y;
    
    /**
     * @param elements
     *            select element
     * @param x
     *            x coordinate
     * @param y
     *            y coordiante
     */
    public MoveElementCommand(SVGElement[] elements, float x, float y)
    {
        this.elements = elements;
        this.x = x;
        this.y = y;
        
    }
    
    @Override
    public void execute()
    {
        // TODO Auto-generated method stub
        
        MoveElementVisitor visitor = new MoveElementVisitor(x, y);
        for (SVGElement element : elements)
        {
            element.acceptVisitor(visitor);
        }
        
    }
    
    @Override
    public void undo()
    {
        // TODO Auto-generated method stub
        MoveElementVisitor visitor = new MoveElementVisitor(-x, -y);
        for (SVGElement element : elements)
        {
            element.acceptVisitor(visitor);
        }
    }
    
    /** Visitor implementing the move logic for each element type. */
    private static class MoveElementVisitor implements SVGVisitor
    {
        
        private float dx, dy;
        
        public MoveElementVisitor(float dx, float dy)
        {
            this.dx = dx;
            this.dy = dy;
        }
        
        public void visitGroup(SVGGroup group)
        {
            for (SVGElement child : group)
                child.acceptVisitor(this);
        }
        
        public void visitRect(SVGRectElement rect)
        {
            rect.getX().setValue(rect.getX().getValue() + dx);
            rect.getY().setValue(rect.getY().getValue() + dy);
            
        }
        
        public void visitCircle(SVGCircleElement circle)
        {
            circle.getCX().setValue(circle.getCX().getValue() + dx);
            circle.getCY().setValue(circle.getCY().getValue() + dy);
            
        }
        
        public void visitLine(SVGLineElement line)
        {
            line.getX1().setValue(line.getX1().getValue() + dx);
            line.getY1().setValue(line.getY1().getValue() + dy);
            line.getX2().setValue(line.getX2().getValue() + dx);
            line.getY2().setValue(line.getY2().getValue() + dy);
            
        }
        
    }
    
}
